package com.bole.callback;

import com.bole.feign.PayLogFeign;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

//监听事务
@RocketMQTransactionListener(txProducerGroup = "paySuccess")
public class TxMessageCallback implements RocketMQLocalTransactionListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PayLogFeign payLogFeign;

    /**
     * 执行本地事务的方法 操作数据库
     *
     * @param message
     * @param o
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            //业务处理
            String msg = new String((byte[]) message.getPayload());
            //修改订单和payLog的状态
            // payLogService.updatePayByOutTradeNo((TbPayLogDto) o);
            //payLogFeign.savePayLog((TbPayLogDto)o);
            System.out.println("将要发送的消息" + msg);
            System.out.println("本地事务需要的参数" + o);
        } catch (Exception e) {
            e.printStackTrace();
            //处理异常返回ROLLBACK 将消息id保存到redis中
            redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"), "2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //处理成功返回COMMIT 将消息id保存到redis中 消费者可以进行消费
        redisTemplate.opsForValue().set(message.getHeaders().get("TRANSACTION_ID"), "1");
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 回查
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //通过事务id获取 redis中 对应的本地事务执行状态  已处理提交 否则回滚
        String status = (String) redisTemplate.opsForValue().
                get(message.getHeaders().get("TRANSACTION_ID").toString());
        if ("1".equals(status)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if ("2".equals(status)) {
            //继续处理，或者直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}